﻿using System;
using System.Collections.Generic;
using System.Web;


namespace CCPSIP.Reg
{
    /// <summary>CCPSIP_002：手機門號認證 API (+國碼)</summary>
    /// UserCountry = 申請人手機門號國碼。
    /// UserPhone = 申請人手機門號。
    /// AuthCode = 以 SMS 簡訊傳送的認證碼。(目前為6位數字)
    /// UUID = 註冊裝置的 UUID。
    /// deviceToken = 註冊 Device 的 APNs Token 或 GCM Registration ID。
    /// devEnv = 開發測試版為'Y'，正式發行版為'N'。

    public class auth : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";


            try
            {
                //【01】取得POST參數
                //
                string UserCountry = req.Form["UserCountry"];//申請人手機國碼
                string UserPhone = req.Form["UserPhone"];//申請人手機
                string AuthCode = req.Form["AuthCode"];  //驗證碼
                string UUID = req.Form["UUID"];//Device UUID
                string deviceToken = req.Form["deviceToken"];//Device Push Token
                string devEnv = req.Form["devEnv"];//是否為開發測試版

                try
                {
                    AuthCode = AuthCode.Trim();
                    UserPhone = ChrisKit.CleanPhoneNum(UserPhone);//清理手機門號

                    if (UUID.Length < 15)
                        throw new Exception();
                }
                catch
                {
                    throw new Exception("Error_01: Parameter Error");//參數錯誤
                }

                string PushType = PushKit.ToPushType(devEnv, deviceToken);


                //【01-1】國碼前處理
                //
                if (string.IsNullOrEmpty(UserCountry))
                {
                    UserCountry = "886";//預設台灣
                }
                else if (UserCountry.StartsWith("+"))
                {
                    UserCountry = UserCountry.Substring(1);//去開頭"+"
                }

                if (UserPhone.StartsWith("0"))
                {
                    UserPhone = UserPhone.Substring(1);//去開頭"0"
                }


                //【02】檢查驗證碼
                //
                int ApplyID = OracleKitReg.ValidateRegAuth(UserCountry, UserPhone, AuthCode);
                if (ApplyID < 0)
                {
                    throw new Exception("Error_02: Auth code is wrong.");//認證失敗
                }


                //【03】記錄Device UUID
                //
                OracleKitReg.InsertRegAuthDevice(ApplyID, UUID, deviceToken, PushType);


                //【04】通知Push Service
                //
                PushKit.WakePushAsync(PushKit.PushType.Msg);


                resultStr = "OK";
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
